package com.kun.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kun.dto.SysTenantBo;
import com.kun.dto.SysTenantDTO;
import com.kun.entity.SysTenant;
import com.kun.helper.TenantHelper;
import com.kun.service.SysTenantService;
import com.kun.util.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author kun.li
 */
@RestController
@RequestMapping("tenant")
@RequiredArgsConstructor
@Tag(name = "租户管理")
public class TenantController {

    private final SysTenantService sysTenantService;

    @Operation(summary = "租户分页")
    @PostMapping("pageTenant")
    public ResponseResult<Page<SysTenant>> pageTenant(@RequestBody SysTenantDTO sysTenantDTO) {
        Page<SysTenant> sysTenantPage = sysTenantService.page(Page.of(sysTenantDTO.getPage(), sysTenantDTO.getSize()));
        return ResponseResult.success(sysTenantPage);
    }


    @Operation(summary = "获取所有租户")
    @GetMapping("selectList")
    public ResponseResult<List<SysTenant>> selectList() {
        List<SysTenant> sysTenants = sysTenantService.list();
        return ResponseResult.success(sysTenants);
    }


    @PostMapping("saveTenant")
    @Operation(summary = "保存租户信息")
    public ResponseResult<Boolean> saveTenant(@RequestBody SysTenantBo sysTenantBo) {
        return ResponseResult.success(sysTenantService.saveTenant(sysTenantBo));
    }

    @PostMapping("updateTenant")
    @Operation(summary = "更新租户信息")
    public ResponseResult<Boolean> updateTenant(@RequestBody SysTenantBo bo) {
        String tenantId = bo.getTenantId();
        if (ObjectUtil.isNotNull(tenantId) && bo.getTenantId().equals("1")) {
            throw new RuntimeException("不允许操作管理租户");
        }
        return ResponseResult.success(sysTenantService.updateTenant(bo));
    }

    @GetMapping("syncTenantPackage/{tenantId}/{packageId}")
    @Operation(summary = "同步租户套餐")
    public ResponseResult<Boolean> syncTenantPackage(@PathVariable String tenantId, @PathVariable String packageId) {
        Boolean flag=TenantHelper.ignore(()->sysTenantService.syncTenantPackage(tenantId,packageId));
        return ResponseResult.success(flag);
    }


    @DeleteMapping("removeTenant/{id}")
    @Operation(summary = "删除租户")
    public ResponseResult<Boolean> removeTenant(@PathVariable String id) {
        return ResponseResult.success(sysTenantService.removeTenant(id));
    }


    /**
     * 内部系统调用
     * 获取租户信息
     */
    @GetMapping("getSysTenant")
    public SysTenant getSysTenant(String tenantId) {
        return sysTenantService.getOne(Wrappers.<SysTenant>lambdaQuery().eq(SysTenant::getTenantId, tenantId));
    }

}
